import moment from "moment";
import { ref } from "vue";
import { timeSlot } from "@/utils";
import {
  addOrUpdate,
  getRegulateItem,
  confirmRegulate,
  optimizationCalculation
} from "@/api/collaborativeInteractiveRresponse";
import { ElNotification } from "element-plus";
export function setDataHook(
  selValue,
  getMonthDataShowCalener,
  activeVppAndUser
) {
  const setShow = ref(false);

  // function getRandomNumberInRange(start, end) {
  //   const random = Math.random() * (end - start + 1) + start;
  //   return parseFloat(random.toFixed(2));
  // }

  let data = [];
  const times = timeSlot(15);
  const showDataObj = ref([]);
  const keys = ref(
    Array(96)
      .fill(1)
      .map((_, index) => index + 1)
      .map(i => `p${i > 9 ? i : "0" + i}`)
  );
  times.forEach((item, index) => {
    let c = [
      item
      // getRandomNumberInRange(4.9, 5), // 最大值
      // getRandomNumberInRange(3.5, 4.8), // 实际值
      // getRandomNumberInRange(3, 3.5), // 最小值
      // getRandomNumberInRange(0, 6),
      // getRandomNumberInRange(0, 6),
      // getRandomNumberInRange(0, 6)
    ];
    data.push(c);
    showDataObj.value.push({
      name: item,
      value: null,
      index: index,
      keys: keys.value[index]
    });
  });
  const showDataBase = ref(new Array(96).fill(null));
  const chartOptions = ref({
    color: [
      "#fac858",
      "#91cc75",
      "#ee6666",
      "#3ba272",
      "#fc8452",
      "#9a60b4",
      "#ea7ccc"
    ],
    title: {
      show: true,
      text: `${selValue.value} 日前计划设置`,
      left: "center"
    },
    grid: {},
    legend: {
      show: true,
      top: "10%",
      // data: ["响应能力", "日前计划", "实际", "APC"]
      data: ["日前计划"]
    },
    dataZoom: [
      {
        type: "inside",
        start: 0,
        end: 100
      },
      {
        show: true,
        type: "slider",
        top: "90%",
        start: 0,
        end: 100
      }
    ],
    tooltip: {
      trigger: "axis",
      formatter(p) {
        let str = "";
        p.forEach(item => {
          str += `
            ${item.marker}${item.seriesName}： <br/>
            ${item.data.name}：${item.data.value ? item.data.value + "MW" : "--"}
            `;
        });
        return str;
        // if (
        //   p.length >= 2 &&
        //   p[0].seriesType === "candlestick" &&
        //   p[1].seriesType === "candlestick"
        // ) {
        //   let markerOne = p[0].marker;
        //   let max = p[0].value[1];
        //   let min = p[0].value[3];
        //   let str = "";
        //   p.forEach((item, index) => {
        //     if (index > 1) {
        //       str += `
        //     ${item.marker}${item.seriesName}: ${item.value}<br/>
        //     `;
        //     }
        //   });
        //   return (
        //     `${markerOne}响应能力<br/>
        //     上限：${max}<br/>
        //   下限：${min}<br/>
        //   ` + str
        //   );
        // } else {
        //   let str = "";
        //   p.forEach(item => {
        //     str += `
        //     ${item.marker}${item.seriesName}: ${item.value}<br/>
        //     `;
        //   });
        //   return str;
        // }
      }
      // axisPointer: {
      //   type: 'cross'
      // }
    },
    xAxis: {
      splitLine: {
        show: false
      },
      data: data.map(item => item[0])
    },
    yAxis: [
      {
        name: "kW",
        nameLocation: "end",
        splitLine: {
          show: false
        },
        axisLine: {
          show: true
        }
      }
    ],
    series: [
      // {
      //   name: "响应能力",
      //   type: "candlestick",
      //   // 最大值  最大值 - 1 最小值 最小值+1
      //   data: data.map(item => {
      //     return [item[1], item[1] - 0.01, item[3], item[3] + 0.01];
      //   })
      // },
      // {
      //   name: "响应能力下限",
      //   type: "candlestick",
      //   // 最小值+1  最小值 - 1 最小值 - 1  最小值+1
      //   data: data.map(item => {
      //     return [
      //       item[3] + 0.01,
      //       item[3] - 0.01,
      //       item[3] - 0.01,
      //       item[3] + 0.01
      //     ];
      //   })
      // },
      {
        name: "日前计划",
        type: "line",
        smooth: true,
        // 实际值
        data: showDataObj.value
      }
      // {
      //   name: "实际",
      //   type: "line",
      //   lineStyle: {
      //     opacity: 0.2
      //   },
      //   // 实际值
      //   data: data.map(item => {
      //     return item[5];
      //   })
      // },
      // {
      //   name: "APC",
      //   type: "line",
      //   lineStyle: {
      //     opacity: 0.2
      //   },
      //   // 实际值
      //   data: data.map(item => {
      //     return item[6];
      //   })
      // }
    ]
  });
  const resetData = () => {
    let data = [];
    // 一行八个
    for (let i = 0; i < 12; i++) {
      let item = [];
      for (let j = 0; j < 16; j++) {
        if (j % 2 === 0) {
          item[j] = times[j / 2 + i * 8];
        }
        if (j % 2 !== 0) {
          item[j] = "";
        }
      }
      // for(let z=0;z<times.length;z++) {
      //
      // }
      data.push(item);
    }
    return data;
  };
  const resetRules = () => {
    let data = {};
    for (let i = 0; i < 12; i++) {
      for (let j = 0; j < 16; j++) {
        if (j % 2 !== 0) {
          data[`${i}.${j}`] = [
            { required: false, message: "请输入值", trigger: "blur" },
            {
              trigger: "blur",
              validator: (rule: any, value: any, callback: any) => {
                if (value) {
                  if (/^\d+(\.\d{1,2})?$/.test(value) === false) {
                    callback(new Error("请输入正确的数值!"));
                    return;
                  }
                }
                callback();
                // /^\d+(\.\d{1,2})?$/
              }
            }
          ];
        }
      }
    }
    return data;
  };
  const setDataForm = ref(resetData());
  const setDataFormRules = ref(resetRules());
  const setValue = (e, rowIndex, colIndex) => {
    let index = rowIndex * 8 + (colIndex - 1) / 2;
    showDataBase.value[index] = e.target.value;
    showDataObj.value.forEach(item => {
      if (item.index === index) {
        item.value = e.target.value;
      }
    });
  };
  const setFormRef = ref(null);
  const cancelSet = () => {
    showDataBase.value = new Array(96).fill(null);
    showDataObj.value.forEach(item => {
      item.value = null;
    });
    setDataForm.value = resetData();
    setFormRef.value && setFormRef.value.clearValidate();
    setShow.value = false;
  };
  const handleCloseSetData = () => {
    cancelSet();
  };

  const setDefaultData = data => {
    for (let i = 0; i < keys.value.length; i++) {
      showDataBase.value[i] = data[keys.value[i]] || null;
      showDataObj.value.forEach(j => {
        if (j.keys === keys.value[i]) {
          j.value = data[keys.value[i]] || null;
        }
      });
    }
    let z = [1, 3, 5, 7, 9, 11, 13, 15];
    for (let i = 0; i < setDataForm.value.length; i++) {
      for (let j = 0; j < z.length; j++) {
        setDataForm.value[i][z[j]] = showDataBase.value[i * 8 + (z[j] - 1) / 2];
      }
    }
  };
  const dayData = ref(null);
  const getDataByDay = async () => {
    return new Promise(async resolve => {
      let data = await getRegulateItem({
        date: selValue.value,
        vppId: activeVppAndUser.value[0],
        vppUserId: activeVppAndUser.value[1]
      });

      if (!data) {
        data = {
          id: undefined,
          dataDate: selValue.value + " 00:00:00",
          dataType: 1,
          vppId: activeVppAndUser.value[0],
          vppUserId: activeVppAndUser.value[1]
        };
        keys.value.forEach(key => {
          data[key] = undefined;
        });
      }
      resolve(data);
    });
  };
  const setData = async () => {
    // 点击编制
    setShow.value = true;
    chartOptions.value.title.text = `${selValue.value} 日前计划设置`;
    dayData.value = await getDataByDay();
    setDefaultData(dayData.value);
  };
  const submitSet = () => {
    setFormRef.value.validate(async valid => {
      if (valid) {
        let data = {
          id: dayData.value.id || undefined,
          dataDate: dayData.value.dataDate,
          dataType: 1,
          vppId: dayData.value.vppId,
          vppUserId: dayData.value.vppUserId,
          timestamp: moment().format("YYYY-MM-DD HH:mm:ss")
        };
        keys.value.forEach((key, index) => {
          data[key] = showDataBase.value[index] || undefined;
        });
        await addOrUpdate(data);
        ElNotification({
          title: "系统提示",
          message: data.id ? "修改编制成功" : "新增编制成功",
          type: "success"
        });
        handleCloseSetData();
        getMonthDataShowCalener();
      }
    });
  };
  const submitData = async () => {
    // 提交某一天的数据  先获取
    await confirmRegulate(await getDataByDay());
    ElNotification({
      title: "系统提示",
      message: "提交成功",
      type: "success"
    });
    getMonthDataShowCalener();
  };
  const jisuan = async () => {
    await optimizationCalculation({
      vppId: activeVppAndUser.value[0],
      vppUserId: activeVppAndUser.value[1],
      date: selValue.value
    });
    getMonthDataShowCalener();
  };
  return {
    setShow,
    setData,
    handleCloseSetData,
    chartOptions,
    setDataForm,
    setDataFormRules,
    setValue,
    setFormRef,
    cancelSet,
    submitSet,
    setDefaultData,
    dayData,
    getDataByDay,
    submitData,
    jisuan
  };
}
